export function encrypt(str: string, key: string) {
  const encoded = encodeURIComponent(str)
  const keyBytes = new TextEncoder().encode(key)
  const resultBytes = []
  let j = 0

  for (let i = 0; i < encoded.length; i++) {
    const char = encoded[i]
    const charCode = char.charCodeAt(0)
    const keyByte = keyBytes[j % keyBytes.length]
    const encryptedByte = (charCode + keyByte) % 256
    resultBytes.push(encryptedByte)
    j++
  }

  const encryptedArray = new Uint8Array(resultBytes)
  const encryptedString = btoa(String.fromCharCode(...encryptedArray))
  return encryptedString
}

export function decrypt(str: string, key: string) {
  const encryptedArray = Uint8Array.from(atob(str), (c) => c.charCodeAt(0))
  const keyBytes = new TextEncoder().encode(key)
  const resultBytes = []
  let j = 0

  for (let i = 0; i < encryptedArray.length; i++) {
    const encryptedByte = encryptedArray[i]
    const keyByte = keyBytes[j % keyBytes.length]
    const decryptedByte = (encryptedByte - keyByte + 256) % 256
    resultBytes.push(decryptedByte)
    j++
  }

  const decryptedArray = new Uint8Array(resultBytes)
  const decryptedString = decodeURIComponent(String.fromCharCode(...decryptedArray))
  return decryptedString
}
